package com.yuhf.util.db;

import com.yuhf.util.db.exception.DaoException;
import lombok.extern.log4j.Log4j;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


/**
 * @author yuhf
 */
@Log4j
public class DBConnection {

    private static final String DRIVER_CLASS_NAME;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    private static ThreadLocal<Connection> connections=new ThreadLocal();

    static{
        Properties prop=new Properties();
        try {
            File directory = new File(".");
            String filePath = directory.getAbsolutePath();
            log.debug("filePath:"+filePath+"\\jdbc.properties");
            InputStream is = new BufferedInputStream(new FileInputStream(filePath+"\\jdbc.properties"));
            prop.load(is);
        } catch (IOException e) {
            log.error("jdbc.properties file not found.message is "+e.getMessage());
        }
        DRIVER_CLASS_NAME=prop.getProperty("jdbc.driverClassName");
        URL=prop.getProperty("jdbc.url");
        USERNAME=prop.getProperty("jdbc.userName");
        PASSWORD=prop.getProperty("jdbc.password");
        try {
            Class.forName(DRIVER_CLASS_NAME);
        } catch (ClassNotFoundException e) {
            log.error("Class file not found.message is "+e.getMessage());
        }
    }

    public static Connection getConnection(){
        Connection connection= connections.get();
        try {
            if(null==connection||connection.isClosed()) {
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            }
        } catch (SQLException e) {
            log.error("database connection error.message is "+e.getMessage());
            throw new DaoException("数据库连接错误！");
        }
        connections.set(connection);
        return connection;
    }

    public static void closeConnection(Connection connection){
        if(null!=connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
